package com.rivues.module.manage.web.handler.calendar;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.eigenbase.xom.MetaDef.Model;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.rivues.core.RivuDataContext;
import com.rivues.module.manage.web.service.AccountService;
import com.rivues.module.platform.web.exception.BusinessException;
import com.rivues.module.platform.web.handler.Handler;
import com.rivues.module.platform.web.handler.RequestData;
import com.rivues.module.platform.web.handler.ResponseData;
import com.rivues.module.platform.web.interceptor.LogIntercreptorHandler;
import com.rivues.module.platform.web.model.Organ;
import com.rivues.module.platform.web.model.Role;
import com.rivues.module.platform.web.model.SystemCalendar;
import com.rivues.module.platform.web.model.User;
import com.rivues.module.platform.web.model.UserOrgan;
import com.rivues.module.platform.web.model.UserRole;
import com.rivues.module.report.web.model.PublishedReport;
import com.rivues.util.RivuTools;
import com.rivues.util.exception.ReportException;
import com.rivues.util.iface.authz.UserAuthzFactory;
import com.rivues.util.iface.report.ReportFactory;
import com.rivues.util.local.LocalTools;
import com.rivues.util.service.cache.CacheHelper;
  
@Controller  
@RequestMapping("/{orgi}/manage/calendar")  
public class CalendarController extends Handler{
	private final Logger logger = LoggerFactory.getLogger(CalendarController.class);
    @RequestMapping(value="/index" , name="index" , type="manage",subtype="calendar")
    public ModelAndView index(HttpServletRequest request , @PathVariable String orgi , @ModelAttribute RequestData data) throws Exception{ 
    	ModelAndView modelView = request(super.createManageTempletResponse("/pages/manage/calendar/index") , orgi) ;
    	DetachedCriteria criteria = DetachedCriteria.forClass(SystemCalendar.class).add(Restrictions.eq("orgi",orgi)).addOrder(Order.asc("dateflag"));
    	modelView.addObject("calendars",super.getService().findAllByCriteria(criteria));
    	return modelView;
    }
    
    
    @RequestMapping(value="/calendaradd" , name="calendaradd" , type="manage",subtype="calendar")
    public ModelAndView calendaradd(HttpServletRequest request , @PathVariable String orgi , @ModelAttribute RequestData data) throws Exception{ 
    	ModelAndView modelView = request(new ResponseData("/pages/manage/calendar/calendaredit") , orgi) ;
    	return modelView;
    }
    
    @RequestMapping(value="/{calendarid}/calendaredit" , name="calendaredit" , type="manage",subtype="calendar")
    public ModelAndView calendaredit(HttpServletRequest request , @PathVariable String orgi , @ModelAttribute RequestData data,@PathVariable String calendarid) throws Exception{ 
    	ModelAndView modelView = request(new ResponseData("/pages/manage/calendar/calendaredit") , orgi) ;
    	SystemCalendar calendar = (SystemCalendar)super.getService().getIObjectByPK(SystemCalendar.class, calendarid);
    	modelView.addObject("calendar", calendar);
    	return modelView;
    }
    
    @RequestMapping(value="/calendaraddo" , name="calendaraddo" , type="manage",subtype="calendar")
    public ModelAndView calendaraddo(HttpServletRequest request , @PathVariable String orgi ,@Valid SystemCalendar calendar) throws Exception{ 
    	ResponseData responseData = new ResponseData(new StringBuffer().append("redirect:/{orgi}/manage/calendar/index.html?msgcode=S_CALENDAR_000001").toString()) ;
    	int count =  super.getService().getCountByCriteria(DetachedCriteria.forClass(SystemCalendar.class).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("dateflag",calendar.getDateflag())));
    	if(count>0){
    		responseData.setPage(new StringBuffer().append("redirect:/{orgi}/manage/calendar/index.html?msgcode=E_CALENDAR_000001").toString());
    	}else{
    		calendar.setCreatetime(new Date());
        	calendar.setUserid(super.getUser(request).getId());
        	calendar.setOrgi(orgi);
        	super.getService().saveIObject(calendar);
    	}
    	
    	return request(responseData, orgi);
    }
    
    
    @RequestMapping(value="/calendareditdo" , name="calendareditdo" , type="manage",subtype="calendar")
    public ModelAndView calendareditdo(HttpServletRequest request , @PathVariable String orgi ,@Valid SystemCalendar calendar) throws Exception{ 
    	ResponseData responseData = new ResponseData(new StringBuffer().append("redirect:/{orgi}/manage/calendar/index.html?msgcode=S_CALENDAR_000003").toString()) ;
    	SystemCalendar calen = (SystemCalendar)super.getService().getIObjectByPK(SystemCalendar.class, calendar.getId());
    	int count =  super.getService().getCountByCriteria(DetachedCriteria.forClass(SystemCalendar.class).add(Restrictions.eq("orgi",orgi)).add(Restrictions.ne("id",calendar.getId())).add(Restrictions.eq("dateflag",calendar.getDateflag())));
    	if(count>0){
    		responseData.setPage(new StringBuffer().append("redirect:/{orgi}/manage/calendar/index.html?msgcode=E_CALENDAR_000003").toString());
    	}else{
    		calen.setDateflag(calendar.getDateflag());
    		calen.setDatetype(calendar.getDatetype());
        	super.getService().updateIObject(calen);
    	}
    	
    	return request(responseData, orgi);
    }
    @RequestMapping(value="/{calendarid}/calendardelo" , name="calendardelo" , type="manage",subtype="calendar")
    public ModelAndView calendardelo(HttpServletRequest request , @PathVariable String orgi ,@PathVariable String calendarid) throws Exception{ 
    	ResponseData responseData = new ResponseData(new StringBuffer().append("redirect:/{orgi}/manage/calendar/index.html?msgcode=S_CALENDAR_000004").toString()) ;
    	SystemCalendar calendar = (SystemCalendar)super.getService().getIObjectByPK(SystemCalendar.class, calendarid);
    	super.getService().deleteIObject(calendar);
    	
    	return request(responseData, orgi);
    }
    
    @RequestMapping(value="/calendarimport" , name="calendarimport" , type="manage",subtype="account")
    public ModelAndView calendarimport(HttpServletRequest request , @PathVariable String orgi){  
    	ResponseData responseData = new ResponseData("/pages/manage/calendar/calendarimport") ; 
    	ModelAndView modelView = request(responseData , orgi);
    	return modelView;
    }
    
    /**
     * 用户数据导入
     * @param request
     * @param orgi
     * @param file
     * @param id
     * @return
     */
    @RequestMapping(value="/calendarimportdo" , name="calendarimportdo" , type="manage",subtype="account")
    public ModelAndView calendarimportdo(HttpServletRequest request , @PathVariable String orgi,    @RequestParam MultipartFile file , @Valid String freshold)throws Exception{
    	ResponseData responseData = new ResponseData(new StringBuffer().append("redirect:/{orgi}/manage/calendar/index.html?msgcode=S_CALENDAR_000002").toString()) ;
    	POIFSFileSystem pofs = new POIFSFileSystem(file.getInputStream());
		HSSFWorkbook workbook = new HSSFWorkbook(pofs);
		Sheet sheet = workbook.getSheetAt(0);
		SystemCalendar calendar = null;
		SystemCalendar calendartemp = null;
		
		List<SystemCalendar> canlendars = super.getService().findAllByCriteria(DetachedCriteria.forClass(SystemCalendar.class).add(Restrictions.eq("orgi",orgi)));
		if(sheet!=null){
			for (int i = 1; i <= sheet.getLastRowNum(); i++) {
				calendar = new SystemCalendar();
				calendar.setCreatetime(new Date());
	        	calendar.setUserid(super.getUser(request).getId());
	        	calendar.setOrgi(orgi);
				Cell cell = sheet.getRow(i).getCell(0);
				String dateflag = this.getStringCellValue(sheet.getRow(i).getCell(0));
				String datetype = this.getStringCellValue(sheet.getRow(i).getCell(1));
				calendar.setDateflag(dateflag);
				if(!StringUtils.isBlank(datetype)){
					calendar.setDatetype(Integer.parseInt(datetype));
				}else{
					calendar.setDatetype(0);
				}
				boolean flag = true;
				for (int j = 0; j < canlendars.size(); j++) {
					calendartemp = canlendars.get(j);
					if(calendartemp.getDateflag().equals(dateflag)){
						flag = false;
						break;
					}
				}
				if(flag){
					super.getService().saveIObject(calendar);
				}else{
					if("checked".equals(freshold)){
						if(!StringUtils.isBlank(datetype)){
							calendartemp.setDatetype(Integer.parseInt(datetype));
							super.getService().updateIObject(calendartemp);
						}
						
					}
				}
			}
		}
    	
    	ModelAndView modelView = request(responseData , orgi);
    	return modelView;
    }
    
    protected String getStringCellValue(Cell cell) {
    	if (cell == null) return "";
    	cell.setCellType(Cell.CELL_TYPE_STRING);
    	String strCell = cell.getStringCellValue();
        return StringUtils.isNotBlank(strCell)?StringUtils.trim(strCell):strCell;
    }
} 